import type { Context, Next } from "koa";
import { routeConfig, z, body, middlewares } from "koa-swagger-decorator";
import { AUTH_KEY } from "../common/swagger-extra.ts";
import userService from "../service/user.service.ts";
import userMiddleware from "@/middleware/use.middleware.ts";
import authMiddleware from "@/middleware/auth.middleware.ts";
import uploadService from "@/service/upload.service.ts";
// 注册请求体验证
const RegisterSchema = z.object({
  username: z.string().min(3).max(50),
  password: z.string().min(6),
});

// 注册成功返回的数据结构
const RegisterSuccessData = z.object({
  id: z.string(),
  username: z.string(),
  createdAt: z.string().datetime(),
});
// ... existing code ...
const GetUserListSchema = z.object({
  current: z.coerce.number().min(1).default(1),
  pageSize: z.coerce.number().min(1).default(10),
  username: z.string().nullable().optional(), // 可选字符串
  status: z.coerce.number().nullable().optional(), // 可选数字
});
// 批量删除
const BatchDeleteSchema = z.object({
  ids: z.array(z.number()), // 数字数组
});
const updateSchema = z.object({
  id: z.number(),
  username: z.string().min(3).max(50),
  password: z.string().min(6),
  email: z.string().nullable().optional(),
  phone: z.string().nullable().optional(),
  avatar: z.string().nullable().optional(),
  status: z.number().nullable().optional(),
  version: z.number(),
});

export class UserController {
  @routeConfig({
    method: "post",
    path: "/user/add",
    summary: "创建用户",
    tags: ["用户"],
  })
  @body(RegisterSchema)
  @middlewares([userMiddleware.verifyUser, userMiddleware.handlePassword])
  async add(ctx: Context, next: Next) {
    try {
      const requestBody = ctx.request.body as API.userItem;
      const user = requestBody;
      const result = await userService.add(user);
      // 返回通用响应格式
      ctx.body = {
        success: true,
        data: result, // 包含创建的用户数据
        errorMessage: null,
      };
      ctx.status = 201; // 创建成功状态码
    } catch (error: any) {
      // 错误响应格式
      ctx.body = {
        success: false,
        data: null,
        errorMessage: error.message || "注册失败",
      };
      ctx.status = error.status || 400;
    }
  }
  @routeConfig({
    method: "get",
    path: "/user/current",
    summary: "获取当前用户",
    tags: ["用户"],
  })
  @middlewares([authMiddleware.verifyAuth])
  async getCurrent(ctx: Context, next: Next) {
    try {
      const id = ctx.state.user.id;
      const user = await userService.getUserByID(id);
      ctx.body = {
        success: true,
        data: user,
        errorMessage: null,
      };
      ctx.status = 200;
    } catch (error: any) {
      ctx.body = {
        success: false,
        data: null,
        errorMessage: error.message || "获取当前用户失败",
      };
    }
  }
  @routeConfig({
    method: "get",
    path: "/user/list",
    summary: "获取用户列表",
    tags: ["用户"],
    request: {
      query: GetUserListSchema,
    },
  })
  @middlewares([authMiddleware.verifyAuth])
  async get(ctx: Context, next: Next) {
    try {
      // 使用zod验证query参数
      const validatedQuery = GetUserListSchema.parse(ctx.request.query);
      const result = await userService.list(validatedQuery as API.userList);

      ctx.body = {
        success: true,
        data: result,
        errorMessage: null,
      };
      ctx.status = 200;
    } catch (error: any) {
      ctx.body = {
        success: false,
        data: null,
        errorMessage: error.message || "获取用户列表失败",
      };
      ctx.status = error.status || 400;
    }
  }
  @routeConfig({
    method: "delete",
    path: "/user/delete",
    summary: "批量删除用户",
    tags: ["用户"],
  })
  @body(BatchDeleteSchema)
  @middlewares([authMiddleware.verifyAuth])
  async delete(ctx: Context, next: Next) {
    try {
      const body = ctx.request.body as { ids: number[] };
      const result = await userService.delete(body.ids);
      // 返回通用响应格式
      ctx.body = {
        success: true,
        data: result,
        errorMessage: null,
      };
      ctx.status = 201;
    } catch (error: any) {
      // 错误响应格式
      ctx.body = {
        success: false,
        data: null,
        errorMessage: error.message || "删除失败",
      };
      ctx.status = error.status || 400;
    }
  }
  @routeConfig({
    method: "put",
    path: "/user/update",
    summary: "更新用户",
    tags: ["用户"],
  })
  @body(updateSchema)
  @middlewares([authMiddleware.verifyAuth])
  async update(ctx: Context, next: Next) {
    try {
      console.log(1);
      const requestBody = ctx.request.body as API.userItem;
      const result = await userService.update(requestBody);
      // 返回通用响应格式
      ctx.body = {
        success: true,
        data: result,
        errorMessage: null,
      };
      ctx.status = 201;
    } catch (error: any) {
      // 错误响应格式
      ctx.body = {
        success: false,
        data: null,
        errorMessage: error.message || "更新失败",
      };
      ctx.status = error.status || 400;
    }
  }
}
